<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <label style="margin-right: 5px">菜品名称：</label>
        <el-input v-model="name" placeholder="请输入菜品名称：" style="width: 15%" clearable @clear="getDishPage"
          @keyup.enter="getDishPage" />
        <label style="margin: 0 10px">菜品分类：</label>
        <el-select v-model="categoryId" placeholder="请选择菜品分类" clearable style="width: 15%" @clear="getDishPage">
          <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <label style="margin: 0 10px">售卖状态</label>
        <el-select v-model="status" placeholder="请选择" clearable style="width: 15%" @clear="getDishPage">
          <el-option v-for="item in STATUS" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-button type="primary" style="margin-left: 10px" @click="getDishPage">查询</el-button>
        <div style="float: right" v-if="userStore.rule !== 'admin'">
          <el-button type="danger" style="margin-left: 20px" @click="deleteHandle('batch', null)"> 批量删除 </el-button>
          <el-button type="primary" style="margin-left: 20px" @click="addHandle"> 新增菜品 </el-button>
        </div>
      </div>
    </template>
    <el-table :data="dishs" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="35" />
      <el-table-column prop="businessName" label="商家" />
      <el-table-column prop="name" label="菜品名称" />
      <el-table-column prop="image" label="图片">
        <template #default="{ row }">
          <el-image style="width: 60px; height: 60px; border: none; cursor: pointer" :src="row.image">
            <template #error>
              <div class="image-slot">
                <img src="../../assets/default.jpg" style="border: none; object-fit: cover;" />
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="菜品分类" />
      <el-table-column prop="price" label="售价">
        <template #default="{ row }">
          <span style="margin-right: 10px">￥{{ (row.price.toFixed(2) * 100) / 100 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template #default="{ row }">
          <div class="status" :class="{ 'stop-status': row.status === 0 }">
            {{ row.status === 0 ? '停售' : '起售' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="操作时间" />
      <el-table-column label="操作" width="240" align="center">
        <template #default="{ row }" v-if="userStore.rule === 'admin'">
          <el-button size="small" @click="statusHandle(row)" :type="row.status == 1 ? 'danger' : 'success'">
            {{ row.status == 1 ? '停售' : '起售' }}
          </el-button>
        </template>
        <template #default="{ row }" v-else>
          <el-button size="small" @click="addHandle(row)">修改</el-button>
          <el-button size="small" @click="deleteHandle('one', row)">删除 </el-button>
          <el-button size="small" @click="statusHandle(row)" :type="row.status == 1 ? 'danger' : 'success'">
            {{ row.status == 1 ? '停售' : '起售' }}
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty />
      </template>
    </el-table>
    <template #footer>
      <!-- 分页条 -->
      <Pagination :page="page" :pageSize="pageSize" :total="total" @onSizeChange="onSizeChange"
        @onPageChange="onPageChange" />
    </template>
  </el-card>
</template>
<script setup lang="ts">
import Pagination from '@/components/Pagination/index.vue'
import { deleteDishAPI, postDishStatusAPI } from '@/api/business/dish'
import { DishResult } from '@/types/dish'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, onMounted } from 'vue'
import { CATEGORY_TYPE, STATUS } from '@/constants'
import { useRouter } from 'vue-router'
const router = useRouter()
// 菜品分页查询
import useDishPage from './useDishPage'
const { name, categoryId, page, pageSize, status, total, dishs, getDishPage } = useDishPage()
// 菜品分类列表
import useCategory from '@/hooks/useCategory'
const { categoryList, getCategorysByType } = useCategory()
import { useUserStore } from '@/stores/userStore'
import { postAdminDishStatusAPI } from '@/api/admin/dish'
const userStore = useUserStore()
onMounted(async () => {
  await Promise.all([getCategorysByType(CATEGORY_TYPE.dish), getDishPage()])
})
const onSizeChange = (num: number) => {
  pageSize.value = num
  getDishPage()
}
const onPageChange = (num: number) => {
  page.value = num
  getDishPage()
}

// 起售/停售
const statusHandle = async (row: any) => {
  const id = row.id
  const status = row.status

  ElMessageBox.confirm('确认要执行此操作吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      if (userStore.rule === 'admin') {
        await postAdminDishStatusAPI(!status ? 1 : 0, id)
      } else {
        await postDishStatusAPI(!status ? 1 : 0, id)
      }
      getDishPage()
      ElMessage.success('修改成功')
    })
    .catch(() => {
      ElMessage.info('已取消')
    })
}
// 添加/修改菜品
const addHandle = (row: DishResult) => {
  if (!row) {
    router.push('/dish/detail')
  } else {
    router.push({ path: '/dish/detail', query: { id: row.id } })
  }
}
// 批量选择删除列表
const multipleSelection = ref<DishResult[]>([])
// 选择
const handleSelectionChange = (val: DishResult[]) => {
  multipleSelection.value = val
  console.log(multipleSelection.value)
}
// 删除
const deleteHandle = (type: string, row: any) => {
  // 批量删除且没有选择项时显示错误消息
  if (type === 'batch' && multipleSelection.value.length === 0) {
    ElMessage.error('请先选择操作对象')
    return
  }

  // 定义一个函数来处理删除逻辑
  const deleteByIds = async (ids: string) => {
    try {
      await deleteDishAPI(ids)
      getDishPage()
      ElMessage.success(type === 'batch' ? '批量删除成功' : '删除成功')
    } catch (err: any) {
      ElMessage.warning('删除失败：' + (err.message || '未知错误'))
    }
  }

  // 根据类型处理不同的删除逻辑
  if (type === 'batch') {
    // 批量删除，不检查单个商品的状态
    const ids = multipleSelection.value.map(item => item.id).join(',')
    ElMessageBox.confirm('确认要删除这些菜品吗?', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteByIds(ids)
    })
  } else {
    // 单个删除，检查商品状态
    if (row && row.status !== 1) {
      ElMessageBox.confirm('确认要删除该菜品吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteByIds(row.id.toString())
      })
    } else {
      ElMessage.warning('起售中的商品不能删除' + (row ? '' : '（无效的删除对象）'))
    }
  }
}
</script>
<style scoped></style>
